import * as c from '@/services/consts';
import * as apiServer from '@/services/vpnServer';
import * as api from '@/services/vpnServerCheck';
import {
  ArrowDownOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  EditOutlined,
} from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Badge,
  Button,
  Descriptions,
  message,
  Popconfirm,
  Space,
  Tag,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
// import VpnServerBatchGroupForm from '../VpnServer/components/BatchChangeGroupForm';
// import VpnServerBatchRemarkForm from './BatchRemarkForm';
import BatchChangeForm from '../VpnServer/components/BatchChangeForm';
import VpnServerEditForm from '../VpnServer/components/VpnServerForm';
import dayjs from 'dayjs';

type VpnServerFormProps = {
  visible: boolean;
  ver: string | undefined;
  groupId: string | undefined;
  onCancel: () => void;
  onCancelAndReload: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel, onCancelAndReload, ver, groupId } = props;

  if (!visible) {
    return null;
  }

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const { hasRight } = useModel('useAuthModel');
  const [myloading, setMyloading] = useState<boolean>(true);
  const [dataSource, setDataSource] = useState<
    API.VpnServerCheckReport | undefined
  >(undefined);
  const [selectIds, setSelectIds] = useState<any[]>([]);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  // const [formBatchGroupVisible, setFormBatchGroupVisible] = useState<boolean>(false);
  // const [formBatchRemarkVisible, setFormBatchRemarkVisible] = useState<boolean>(false);
  const [formBatchChangeVisible, setFormBatchChangeVisible] = useState<boolean>(false);
  const [currentServer, setCurrentServer] = useState<API.VpnServer | undefined>(
    undefined,
  );
  const [serverChecks, setServerChecks] = useState<
    API.VpnServerCheckIpReport[] | undefined
  >(undefined);

  let tableGroupTitle: string = '';
  let tableGroupFont: string = 'normal';

  const loadData = async () => {
    const result = await api.report({ ver, groupId });
    if (result && result.success) {
      setDataSource(result);
    }
    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  // const handleChangeStatus = async (status: boolean) => {
  //   if (selectIds.length < 1) return;
  //   console.log({ keys: selectIds, status: status });
  //   const result = await apiServer.status({ keys: selectIds, status: status });
  //   if (result && result.success === true) {
  //     setSelectIds([]);
  //     actionRef.current?.clearSelected?.();
  //     setMyloading(true);
  //     loadData();
  //     // actionRef.current?.reload();
  //   }
  // };

  // const handleFormBatchGroupSubmit = async (groupIds: string[]) => {
  //   let result: API.Result;
  //   // console.log({ keys: selectIds, groupIds: groupIds });
  //   result = await apiServer.groups({ keys: selectIds, groupIds: groupIds });

  //   if (result && result.success === true) {
  //     actionRef.current?.clearSelected?.();
  //     setFormBatchGroupVisible(false);
  //     setMyloading(true);
  //     loadData();
  //     // actionRef.current?.reload();
  //   }
  // };

  // const handleFormBatchRemarkSubmit = async (remark: string) => {
  //   let result: API.Result;
  //   result = await apiServer.remarks({ keys: selectIds, remark: remark });

  //   if (result && result.success === true) {
  //     actionRef.current?.clearSelected?.();
  //     setFormBatchRemarkVisible(false);
  //     // setMyloading(true);
  //     // loadData();
  //     // actionRef.current?.reload();
  //   }
  // };

  const handleFormSubmit = async (record: API.VpnServer) => {
    if (!record) {
      message.error('参数出错');
      return;
    }
    let result: API.Result = await apiServer.update({
      ...currentServer,
      ...record,
    });

    if (result && result.success === true) {
      setCurrentServer(undefined);
      setFormVisible(false);
      setMyloading(true);
      loadData();
    }
  };

  const handleRemove = async (ver: string | undefined) => {
    if (!ver) {
      message.error('无效版本号');
      return;
    }
    const result = await api.remove({ ver: ver });
    if (result.success) {
      onCancelAndReload();
    }
  };

  const clientColumns: ProColumns<API.VpnServerCheckProgress>[] = [
    {
      title: '检测客户端',
      width:100,
      dataIndex: 'clientName',
    },
    {
      title: '检测客户端IP',
      dataIndex: 'client',
    },
    {
      title: '进度',
      dataIndex: 'percent',
      render: (_, record) => {
        if (record.percent == 100) {
          return '完成';
        } else {
          return `${record.percent} %`;
        }
      },
    },
    {
      title: '开始时间',
      dataIndex: 'createTime',
    },
    {
      title: '最后更新时间',
      dataIndex: 'updateTime',
    },
  ];

  const columns: ProColumns<API.VpnServerCheckServer>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'serverStatus',
      //sorter: (a, b) => (a.serverStatus == true ? 1 : 0) - (b.serverStatus == true ? 1 : 0),
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
      // filters: [{text:'启用', value: true},{text:'禁用', value: false}],
    },
    {
      title: '分组',
      dataIndex: 'groupNames',
      width: 120,
      render: (_, record) => {
        let text = '';
        if (record.groupNames) {
          text = record.groupNames.join(',');
        }
        if (tableGroupTitle != text) {
          tableGroupFont = tableGroupFont == 'blue' ? 'green' : 'blue';
        }
        tableGroupTitle = text; //'bolder'
        // return <div style={{color:tableGroupFont}}><div>{text}</div>{record.protocol ? <Tag>{c.getObjectText(c.VpnGroupProtocols, record.protocol)}</Tag>: ""}</div>;
        return (
          <div style={{ color: tableGroupFont }}>
            {record.protocol ? (
              <div>{c.getObjectText(c.VpnGroupProtocols, record.protocol)}</div>
            ) : (
              ''
            )}
            <div>{text}</div>
          </div>
        );
      },
    },
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      width: 230, //80
      render: (_, record) => {
        return (
          <>
            <div>{record.instanceId}</div>
            <div>{record.name}</div>
          </>
        );
      },
    },
    // {
    //   title: '名称',
    //   dataIndex: 'name',
    //   width: 230,
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 100,
      ellipsis: true,
      render: (_, record) => {
        return record.server?.remark;
      },
    },
    {
      title: '检测',
      dataIndex: 'groupNames',
      render: (_, record) => {
        if (!record.data) {
          return <></>;
        }
        let instCheckIps: API.VpnServerCheckIpReport[] = [];
        return record.data.map((item) => {
          let instCheckIp: API.VpnServerCheckIpReport = {
            client: item.bindIp,
            tcp: true,
            udp: true,
          };
          instCheckIps.push(instCheckIp);
          return (
            <Descriptions
              column={(item.reports?.length ?? 0) + 1}
              style={{ marginBottom: -10 }}
            >
              {item.reports?.map((rep) => {
                instCheckIp.tcp = instCheckIp.tcp && rep.tcp ? true : false;
                instCheckIp.udp = instCheckIp.udp && rep.udp;
                return (
                  <Descriptions.Item>
                    <Tag
                      color={rep.tcp ? 'success' : 'error'}
                      style={{ margin: 0 }}
                    >
                      T
                    </Tag>
                    <Tag
                      color={rep.udp ? 'success' : 'error'}
                      style={{ margin: 0 }}
                    >
                      U
                    </Tag>
                    {rep.client}
                  </Descriptions.Item>
                );
              })}
              <Descriptions.Item>
                <Tag style={{ margin: 0 }}>IP</Tag>
                {item.bindIp}
                {hasRight('vpnserver_update') ? (
                  <a
                    key={`edit_server${item.bindIp}`}
                    onClick={(e) => {
                      setFormVisible(true);
                      setCurrentServer(record.server);
                      setServerChecks(instCheckIps);
                    }}
                  >
                    {' '}
                    <EditOutlined />
                  </a>
                ) : (
                  ''
                )}
              </Descriptions.Item>
            </Descriptions>
          );
        });
      },
    },
  ];

  return (
    <DrawerForm<API.VpnServerCheckModel>
      open={visible}
      title={
        <>
          检测结果 <Tag color="blue">版本：{dataSource?.ver}</Tag>{' '}
          <Tag color="blue">
            下发时间：
            {dayjs(dataSource?.createTime).format('YYYY-MM-DD HH:mm:ss')}
          </Tag>{' '}
          <Tag color="blue">创建人：{dataSource?.createUser}</Tag>
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1500}
      // onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
    >
      <ProTable<API.VpnServerCheckProgress>
        rowKey="client"
        actionRef={actionRef}
        loading={myloading}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={clientColumns}
        expandable={undefined}
        dataSource={dataSource?.progresss}
      />

      <ProTable<API.VpnServerCheckServer>
        rowKey="serverId"
        actionRef={actionRef}
        headerTitle={
          <b>
            检测结果
            {dataSource?.createTime ? (
              dayjs(new Date()).format('YYYY-MM-DD') !=
              dayjs(dataSource?.createTime).format('YYYY-MM-DD') ? (
                <Tag color="error">非当天检测结果</Tag>
              ) : (
                ''
              )
            ) : (
              ''
            )}
            　
            {dataSource?.checkConfig?.uncheckBlock == true ? (
              <Tag color="blue">不检测被墙</Tag>
            ) : (
              ''
            )}
          </b>
        }
        loading={myloading}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={columns}
        expandable={undefined}
        dataSource={dataSource?.data}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                }}
              >
                <span>
                  <Popconfirm
                    key="delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemove(dataSource?.ver);
                    }}
                  >
                    <Button type="primary">删除当前检测</Button>
                  </Popconfirm>
                </span>
                <span>
                  <a
                    target="_blank"
                    key="excel"
                    href={`/admin-api/vpnservercheck/export?ver=${
                      ver ? ver : dataSource?.ver
                    }`}
                  >
                    <ArrowDownOutlined />
                    下载Excel
                  </a>
                </span>
              </Space>
            </>
          ),
        }}
        rowSelection={{
          defaultSelectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectIds(selectedRowKeys);
          },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>

            {/* <span>
              {hasRight('vpnserver_update') ? (
                <Popconfirm
                  key="disableStatus"
                  title="确定要批量禁用服务器？"
                  onConfirm={async () => {
                    handleChangeStatus(false);
                  }}
                >
                  <a>禁用</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('vpnserver_update') ? (
                <Popconfirm
                  key="enableStatus"
                  title="确定要批量启用服务器？"
                  onConfirm={async () => {
                    handleChangeStatus(true);
                  }}
                >
                  <a>启用</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span> */}

            {/* <span>
              {hasRight('vpnserver_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchGroupVisible(true);
                  }}
                >
                  分组
                </a>
              ) : (
                ''
              )}
            </span> */}

            {/* <span>
              {hasRight('vpnserver_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchRemarkVisible(true);
                  }}
                >
                  服务器备注
                </a>
              ) : (
                ''
              )}
            </span> */}

            <span>
              {hasRight('vpnserver_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchChangeVisible(true);
                  }}
                >
                  批量修改服务器信息
                </a>
              ) : (
                ''
              )}
            </span>
            
            <span>
                  <a
                    target="_blank"
                    key="export_excel_select"
                    href={`/admin-api/vpnservercheck/export?ver=${
                      ver ? ver : dataSource?.ver
                    }${selectIds?.map((val) => {return "&ids=" + val})}`}
                  >
                    <ArrowDownOutlined />
                    导出Excel
                  </a>
                </span>
          </Space>
        )}
      />

      {/* <VpnServerBatchGroupForm
        visible={formBatchGroupVisible}
        onSubmit={handleFormBatchGroupSubmit}
        onCancel={() => {
          setFormBatchGroupVisible(false);
        }}
      /> */}
      <VpnServerEditForm
        visible={formVisible}
        defaultGroupIds={undefined}
        loadNodeId={currentServer?.id}
        // current={currentServer}
        checks={serverChecks}
        // onSubmit={handleFormSubmit}
        onSubmit={() =>{
          setCurrentServer(undefined);
          setFormVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setFormVisible(false);
          setCurrentServer(undefined);
        }}
      />
      <BatchChangeForm
        visible={formBatchChangeVisible}
        selectIds={selectIds}
        onSubmit={() => {
          setSelectIds([]);
          setFormBatchChangeVisible(false);
          actionRef.current?.clearSelected?.();
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setFormBatchChangeVisible(false);
        }}
      />
      {/* <VpnServerBatchRemarkForm
        visible={formBatchRemarkVisible}
        onSubmit={handleFormBatchRemarkSubmit}
        onCancel={() => {
          setFormBatchRemarkVisible(false);
        }}
      /> */}
    </DrawerForm>
  );
};

export default VpnServerForm;
